#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API Configuration for Hyperliquid Trading Bot

This module defines the API configuration class for managing
Hyperliquid exchange API credentials and settings.
"""

import os
from typing import Optional
from dataclasses import dataclass


@dataclass
class APIConfig:
    """API configuration for Hyperliquid exchange"""
    
    # Hyperliquid API credentials
    private_key: Optional[str] = None
    wallet_address: Optional[str] = None
    
    # API endpoints
    testnet: bool = True
    api_url: str = "https://api.hyperliquid-testnet.xyz"
    ws_url: str = "wss://api.hyperliquid-testnet.xyz/ws"
    
    # Rate limiting
    max_requests_per_second: int = 10
    max_orders_per_second: int = 5
    
    # Connection settings
    timeout: int = 30
    max_retries: int = 3
    retry_delay: float = 1.0
    
    def __post_init__(self):
        """Initialize API configuration from environment variables"""
        
        # Load from environment variables if not provided
        if self.private_key is None:
            self.private_key = os.getenv('HYPERLIQUID_PRIVATE_KEY')
            
        if self.wallet_address is None:
            self.wallet_address = os.getenv('HYPERLIQUID_WALLET_ADDRESS')
            
        # Set mainnet URLs if not testnet
        if not self.testnet:
            self.api_url = "https://api.hyperliquid.xyz"
            self.ws_url = "wss://api.hyperliquid.xyz/ws"
    
    def validate(self) -> bool:
        """Validate API configuration"""
        
        if not self.private_key:
            raise ValueError("Private key is required")
            
        if not self.wallet_address:
            raise ValueError("Wallet address is required")
            
        return True
    
    @classmethod
    def from_env(cls, testnet: bool = True) -> 'APIConfig':
        """Create API configuration from environment variables"""
        
        return cls(
            private_key=os.getenv('HYPERLIQUID_PRIVATE_KEY'),
            wallet_address=os.getenv('HYPERLIQUID_WALLET_ADDRESS'),
            testnet=testnet
        )
    
    def to_dict(self) -> dict:
        """Convert to dictionary"""
        
        return {
            'private_key': self.private_key,
            'wallet_address': self.wallet_address,
            'testnet': self.testnet,
            'api_url': self.api_url,
            'ws_url': self.ws_url,
            'max_requests_per_second': self.max_requests_per_second,
            'max_orders_per_second': self.max_orders_per_second,
            'timeout': self.timeout,
            'max_retries': self.max_retries,
            'retry_delay': self.retry_delay
        }